package com.axx.android.profile.message.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewStub;

import com.axx.android.LetterApp;
import com.axx.android.R;
import com.axx.android.base.BaseLazyFragment;
import com.axx.android.common.BaseModel;
import com.axx.android.common.Constants;
import com.axx.android.common.SJRefreshView;
import com.axx.android.home.activity.SearchActivity;
import com.axx.android.home.model.SearchWrapper;
import com.axx.android.home.model.User;
import com.axx.android.letter.activity.LetterDetailActivity;
import com.axx.android.letter.activity.RecipientActivity;
import com.axx.android.profile.message.activity.MessageContractActivity;
import com.axx.android.profile.message.activity.MessageLetterAdapter;
import com.axx.android.profile.message.model.ChangeEvent;
import com.axx.android.profile.message.model.MessageLetter;
import com.axx.android.utils.GsonUtils;
import com.axx.android.utils.HttpUtils;
import com.axx.android.utils.MapUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.loadmore.SimpleLoadMoreView;
import com.google.gson.reflect.TypeToken;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 */
public class MessageListFragment extends BaseLazyFragment {


    @Bind(R.id.rv_list)
    RecyclerView rvList;
    @Bind(R.id.refresh_view)
    SJRefreshView refreshView;
    @Bind(R.id.vs_error)
    ViewStub vsError;
    private String direction;
    private String status;

    private int pageNum = 10;
    private int curPage = 1;
    private List<MessageLetter.LetterListBean> listBeanList = new ArrayList<>();
    private MessageLetterAdapter messageLetterAdapter;
    private View viewError;

    public MessageListFragment() {
        // Required empty public constructor
    }


    public static MessageListFragment newInstance(String direction, String status) {

        Bundle args = new Bundle();
        args.putString("direction", direction);
        args.putString("status", status);

        MessageListFragment fragment = new MessageListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            direction = getArguments().getString("direction");
            status = getArguments().getString("status");
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        EventBus.getDefault().unregister(this);
    }

    @Subscribe()
    public void onChanageEvent(ChangeEvent event) {
        direction = event.type;
        curPage = 1;
        refresh();
    }


    private void refresh() {
        refreshView.post(new Runnable() {
            @Override
            public void run() {
                refreshView.setRefreshing(true);
                fetchMessage();
            }
        });
    }

    private void fetchMessage() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("nowpage", curPage + "");
        hashMap.put("pagenum", pageNum + "");
        hashMap.put("userId", LetterApp.authUser.getId());
        hashMap.put("flag", direction);
        hashMap.put("type", status);
        hashMap.put("cityCode", MapUtils.getCity(LetterApp.curLocation.getAdCode()));
        HttpUtils.post(Constants.Url.Letter.LETTER_ME, hashMap, new HttpUtils.SJCallBack() {
            @Override
            public void onSuccess(String result) {
                try {
                    BaseModel<MessageLetter> letterBaseModel = GsonUtils.fromJson(result, new TypeToken<BaseModel<MessageLetter>>() {
                    });
                    if (letterBaseModel.isSuccess()) {
                        showSuccess(letterBaseModel.data.getLetterList());
                    } else {
                        showErrorView();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    refreshView.setRefreshing(false);
                    showErrorView();
                }
            }

            @Override
            public void onError() {
                refreshView.setRefreshing(false);
                showErrorView();
            }
        });
    }

    private void showErrorView() {
        if (viewError == null) {
            viewError = vsError.inflate();
            viewError.findViewById(R.id.btn_retry).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    viewError.setVisibility(View.GONE);
                    refresh();
                }
            });
        } else {
            viewError.setVisibility(View.VISIBLE);
        }

    }


    private void showSuccess(List<MessageLetter.LetterListBean> letterList) {
        refreshView.setRefreshing(false);
        if (viewError != null) {
            viewError.setVisibility(View.GONE);
        }
        if (curPage == 1) {
            messageLetterAdapter.setNewData(letterList);
            messageLetterAdapter.disableLoadMoreIfNotFullPage(rvList);
            messageLetterAdapter.setEmptyView(R.layout.view_default_emtpy, rvList);
        } else {
            int loadCount = letterList.size();
            messageLetterAdapter.addData(letterList);
            if (loadCount < pageNum) {
                messageLetterAdapter.loadMoreEnd();
            } else {
                messageLetterAdapter.loadMoreComplete();
            }

        }
    }


    private void initAdapter() {
        messageLetterAdapter = new MessageLetterAdapter(R.layout.view_item_message_letter, listBeanList);
        rvList.setAdapter(messageLetterAdapter);
        rvList.setLayoutManager(new LinearLayoutManager(getContext()));
        messageLetterAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                curPage++;
                fetchMessage();
            }
        }, rvList);
        rvList.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getContext()).build());
        messageLetterAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                MessageLetter.LetterListBean listBean = messageLetterAdapter.getData().get(position);
                if (listBean.getBodyLetter() != null && listBean.getBodyLetter().size() != 1) {
                    Intent intent = new Intent(getContext(), MessageContractActivity.class);
                    intent.putExtra("data", (Serializable) listBean.getBodyLetter());
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(getContext(), LetterDetailActivity.class);
                    intent.putExtra("id", listBean.getId());
                    intent.putExtra("from", "detail");
                    startActivity(intent);
                }

            }
        });

        messageLetterAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                    String jsonString = null;
                    switch (view.getId()) {
                        case R.id.iv_to_header:
                            jsonString = GsonUtils.toJson(messageLetterAdapter.getData().get(position).getToUser());
                            break;
                        case R.id.iv_from_header:
                            jsonString = GsonUtils.toJson(messageLetterAdapter.getData().get(position).getFromUser());
                            break;
                    }
                    startUserActivity(jsonString);
                }

        });
    }

    private void startUserActivity(String jsonString) {
        try {
            User.UserListBean userListBean1 = GsonUtils.fromJson(jsonString, new TypeToken<User.UserListBean>() {
            });
            Intent intent = new Intent(getActivity(), RecipientActivity.class);
            intent.putExtra("model", userListBean1);
            startActivity(intent);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_message_list;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        initAdapter();
        refresh();
        refreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                curPage = 1;
                fetchMessage();
            }
        });

        EventBus.getDefault().register(this);
    }
}
